'''MisacaDownload

Author: Cauly Kan

Date: 2001.10.19

wiki: /wiki/MisacaConverterDesign.wiki

contact: cauliflower.kan@gmail.com

'''

import urllib
import re

_last = 0

def MisacaDownload(info, out = None):
    
    print "{:>20}".format("MisacaDownload") + ": Downloading '" + info["name"] + "' ",
    
    ret = []
    
    try:
        
        if len(info["urls"]) == 1:
            
            ret.append(urllib.urlretrieve(info["urls"][0], filename = out, reporthook = _urlretrieve_hook)[0])
        
        else:
            
            i = 0
        
            for url in info["urls"]:
                
                if out is None:
            
                    ret.append(urllib.urlretrieve(url, reporthook = _urlretrieve_hook)[0])
                    
                else:
                    
                    ret.append(urllib.urlretrieve(url, filename = "%s.%d" % (out, i), reporthook = _urlretrieve_hook)[0])
    
                    i = i + 1
    
    except urllib.ContentTooShortError:
        
        print "\n{:>20}".format("MisacaDownload") + ": Download failed. "
        
    else:
        
        print "\n{:>20}".format("MisacaDownload") + ": Video successfully downloaded" + ((" to '%s'" % out) if out is not None else ".")
        
    return ret
        
def _urlretrieve_hook(got, block, size):
    
    global _last
    
    progress = ("[%s/%s]" % (_bytes2size(got * block), _bytes2size(size)))
    
    print _backspace(_last) + progress,
    
    _last = len(progress) + 1
    
    return
    
def _bytes2size(bytes):
    
    if bytes > 2097152:
        
        return "%sMb" % int(bytes / 2097152)
     
    elif bytes > 2048:
        
        return "%sKb" % int(bytes / 2048)
    
    else:
        
        return str(bytes)
    
def _backspace(times):
    
    s = "\b"
    
    ret = ""
    
    for i in range(times):
        
        ret = ret + s
        
    return ret
    

            
        
        
        